package com.ku.order.service.mq;

import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.springframework.stereotype.Component;

import java.util.List;

/**
 * @program: rocketMQKill
 * @description: 顺序消息，当订单状态改为已支付后，需要发送消息 创建包裹与物流，
 * 但是创建包裹与物流两者的顺序 不能改变，所以这里需要发送顺序消息
 * @author: JokerKu
 * @create: 2020-05-08 11:14
 **/
@Component
public class OrderlyProducer {

    private DefaultMQProducer producer;

    private static final String NAME_SERVER = "192.168.43.10:9876;192.168.43.9:9876";

    private static final String PRODUCER_GROUP_NAME = "orderly_producer_group";

    //私有构造方法
    private OrderlyProducer() throws MQClientException {
        this.producer = new DefaultMQProducer(PRODUCER_GROUP_NAME);
        this.producer.setNamesrvAddr(NAME_SERVER);
        this.producer.setSendMsgTimeout(3000);

        this.producer.start();
    }

    public void shutdown() {
        this.producer.shutdown();
    }

    public SendResult sendOrderlyMessage(List<Message> messagesList, int messageQueueNumber) {
        SendResult result = null;
        for (Message message : messagesList) {
            try {
                result = this.producer.send(message, new MessageQueueSelector() {
                    @Override
                    public MessageQueue select(List<MessageQueue> list, Message message, Object arg) {
                        Integer queueNumber = (Integer) arg;
                        return list.get(queueNumber);
                    }
                }, messageQueueNumber);
            } catch (MQClientException | RemotingException | MQBrokerException | InterruptedException e) {
                e.printStackTrace();
                return result;
            }
        }
        return result;
    }

}
